2023/12/231150字符

解构赋值

对象数据读取

const obj = {
    name: 'bozai',
    age: 18,
    sex: 'boy',
    address: {
        city: '长治'
    }
}
// 先定义变量,再从对象中拿取同名属性值

               // 换名          添加默认值
const { name, age: year, sex, height = 180, address: { city }} = obj;
console.log(name, year, sex, height, city);  //--> bozai 18 boy 180 长治

数组数据读取

const arr = [1, 2, 3, 4, {a: 'hello'}];
const [n1, , , n4] = arr;  // n1, n4 --> 1 4
const {a} = arr[4];  // a --> "hello"
const [, num2, ...nums] = arr;  // num2, nums --> 2 [3, 4, {a: "hello"}]
let a = 123;
{
    let [a, b, c = 'null'] = [1, 2];  // 当变量被定义过后,容易出现变量已声明的情况。外部可以加一层括号来解决报错
    console.log(a, b, c);
}

数据调换

let a = 1, b = 2;
[a, b] = [b, a];  // 数据调换
console.log(a, b);  //--> 2 1

函数形参使用

function print ({name, age, sex} = obj) {
    console.log(name, age, sex);  //--> bozai 18 boy
}
print();